package com.wechat.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.alibaba.fastjson.JSON;

public class MyUtil {
	private static MyUtil myUtil = null;

	public static MyUtil getMyUtil() {
		if (myUtil == null) {
			synchronized (MyUtil.class) {
				if (myUtil == null) {
					myUtil = new MyUtil();
				}
			}
		}
		return myUtil;
	}

	/**
	 * Sha1加密
	 * 
	 * @dagewang 2017年11月17日
	 */
	public String getSha1(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));

			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * get请求
	 */
	public String sendGet(String url, String... param) throws Exception {
		String result = "";
		BufferedReader in = null;
		StringBuffer params = null;
		if (param != null) {
			for (String str : param) {
				if (params == null) {
					params = new StringBuffer();
					params.append(url + "?" + str);
				} else {
					params.append("&" + str);
				}

			}
		} else {
			params = new StringBuffer();
		}
		String urlNameString = params.toString();
		URL realUrl = new URL(urlNameString);
		URLConnection connection = realUrl.openConnection();
		connection.setRequestProperty("accept", "*/*");
		connection.setRequestProperty("connection", "Keep-Alive");
		connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		connection.connect();
		in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
		if (in != null) {
			in.close();
		}
		return result;
	}

	/**
	 * xml解析
	 * 
	 * @dagewang 2017年11月17日
	 */
	public Map<String, String> xmlToMap(HttpServletRequest request) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> list = root.elements();
		for (Element e : list) {
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}

	/**
	 * 生成xml格式的字符串
	 * 
	 * @dagewang 2017年11月22日
	 */
	public String toXMLText(Map<String, String> map, String content) {
		String fromUserName = map.get("FromUserName");
		String toUserName = map.get("ToUserName");
		StringBuffer sb = new StringBuffer();
		sb.append("<xml> <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>");
		sb.append("<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>");
		sb.append("<CreateTime>" + new Date().getTime() + "</CreateTime>");
		sb.append("<MsgType><![CDATA[text]]></MsgType>");
		sb.append("<Content><![CDATA[" + content + "]]></Content></xml>");
		return sb.toString();
	}

	/**
	 * 解析易源api的调用状态,如果返回空,则表示正常
	 * 
	 * @dagewang 2017年11月23日
	 */
	public String analysisState(int state) {
		String result = null;
		switch (state) {
		case -1:
			result = "对不起,请您输入正确的值,例如 \"cx@shentong@456432432432\"!";
			break;
		case -2:
			result = "无法使用该功能";
			break;
		case -3:
			result = "读取超时";
			break;
		case -1000:
			result = "当前功能正在维护";
			break;
		default:
			if (state < 0) {
				result = "很抱歉,系统内部发生了错误";
			}
			break;
		}
		return result;
	}

	/**
	 * 解析json为Map
	 * 
	 * @dagewang 2017年11月23日
	 */
	@SuppressWarnings("unchecked")
	public Map<Object,Object> jsonToMap(String json) {
		return (Map<Object,Object>)JSON.parse(json);
	}

}
